package com.fs.base.utils;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 文件读取数据工具类
 * @author ACE
 *
 */
public class FileReaderUtils {

    private static BufferedReader reader;
    /**
     * 获取.txt的数据
     * @param path
     * @return
     * @throws Exception
     */
    public static List<String> readTxt(String path) throws Exception{
        List<String> list = new ArrayList<String>();
        File f = new File(path);
        InputStreamReader read = new InputStreamReader(new FileInputStream(f),"GBK");
        BufferedReader bufferedReader = new BufferedReader(read);
        String lineTxt = null;
        while((lineTxt = bufferedReader.readLine()) != null){
            list.add(lineTxt);
        }
        read.close();
        return list;
    }


    /**
     * 获取.xls的数据
     * 返回List<List<String>>  List(行数据)<List<String>>(单元格数据)
     * @param path
     * @return
     * @throws Exception
     */
    public static  List<List<String>> readXls(String path) throws Exception {
        InputStream is = new FileInputStream(path);
        // HSSFWorkbook 标识整个excel
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
        List<List<String>> result = new ArrayList<List<String>>();
        int size = hssfWorkbook.getNumberOfSheets();
        // 循环每一页，并处理当前循环页
        for (int numSheet = 0; numSheet < size; numSheet++) {
            // HSSFSheet 标识某一页
            HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
            if (hssfSheet == null) {
                continue;
            }
            // 处理当前页，循环读取每一行
            for (int rowNum = 0; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                // HSSFRow表示行
                HSSFRow hssfRow = hssfSheet.getRow(rowNum);
                if(hssfRow==null){
                    continue;
                }else{
                    int minColIx = hssfRow.getFirstCellNum();
                    int maxColIx = hssfRow.getLastCellNum();
                    List<String> rowList = new ArrayList<String>();
                    // 遍历改行，获取处理每个cell元素
                    for (int colIx = minColIx; colIx < maxColIx; colIx++) {
                        // HSSFCell 表示单元格
                        HSSFCell cell = hssfRow.getCell(colIx);
                        if (cell == null) {
                            rowList.add("");
                            continue;
                        }
                        //如果数据为空就不添加
                        String value = getStringVal(cell);
                        rowList.add(value);
                    }
                    if(rowList.size()>0){
                        result.add(rowList);
                    }
                }
            }
        }
        return result;
    }
    /**
     * 获取.xlsx的数据
     * 返回List<List<String>>  List(行数据)<List<String>>(单元格数据)
     * @param path
     * @return
     * @throws Exception
     */
    public static  List<List<String>> readXlsx(String path) throws Exception {
        InputStream is = new FileInputStream(path);
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);
        List<List<String>> result = new ArrayList<List<String>>();
        // 循环每一页，并处理当前循环页
        for (XSSFSheet xssfSheet : xssfWorkbook) {
            if (xssfSheet == null || xssfSheet.getLastRowNum() == 0) {
                continue;
            }
            // 处理当前页，循环读取每一行
            for (int rowNum = 0; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
                XSSFRow xssfRow = xssfSheet.getRow(rowNum);
                int minColIx = xssfRow.getFirstCellNum();
                int maxColIx = xssfRow.getLastCellNum();
                List<String> rowList = new ArrayList<String>();
                for (int colIx = minColIx; colIx < maxColIx; colIx++) {
                    XSSFCell cell = xssfRow.getCell(colIx);
                    if (cell == null) {
                        rowList.add("");
                        continue;
                    }
                    String value = getStringVal(cell);
                    rowList.add(value);
                }
                if(rowList.size()>0){
                    result.add(rowList);
                }
            }
        }
        return result;
    }
    /**
     * 获取.csv文件数据
     * @param path
     * @return List<List<String>>  List(行数据)<List<String>>(单元格数据)
     * @throws Exception
     */
    public static List<List<String>> readCsv(String path) throws Exception{
        reader = new BufferedReader(new InputStreamReader(new FileInputStream(path),"GBK"));
        String line = "";
        List<List<String>> lists = new ArrayList<>();
        while ((line = reader.readLine()) != null) {
            List<String> list = new ArrayList<>();
            String[] str = line.split(",");
            for(int i=0;i<str.length;i++){
                list.add(str[i]);
            }
            lists.add(list);
        }
        reader.close();
        return lists;
    }

    private static String getStringVal(Cell cell) {
        try {
            switch (cell.getCellType()) {//获取类型，将其都转换为字符串
                case Cell.CELL_TYPE_BOOLEAN:
                    return new String((cell.getBooleanCellValue() ? "TRUE" : "FALSE").getBytes(),"UTF-8");
                case Cell.CELL_TYPE_FORMULA:
                    return new String(cell.getCellFormula().getBytes(),"UTF-8");//解决乱码
                case Cell.CELL_TYPE_NUMERIC:
                    if (HSSFDateUtil.isCellDateFormatted(cell)) {
                        Date date = cell.getDateCellValue();
                        return DateFormatUtils.format(date, "yyyy-MM-dd");
                    } else {
                        DecimalFormat df = new DecimalFormat("#.##");
                        return df.format(cell.getNumericCellValue());
                    }
                    //cell.setCellType(Cell.CELL_TYPE_STRING);
                    //return new String(cell.getStringCellValue().getBytes(),"UTF-8");
                case Cell.CELL_TYPE_STRING:
                    return new String(cell.getStringCellValue().getBytes(),"UTF-8");
                default:
                    return "";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
}
